﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Ftp;
using UtilZ.Dotnet.Ex.Communication.Net.Web.JWT;
using UtilZ.Dotnet.Ex.Config;
using UtilZ.Dotnet.Ex.Json;
using UtilZ.Dotnet.Ex.Log;

namespace ConAppCore
{
    internal class TestFtpServer
    {

        //header（头部）、payload（载荷）和signature（签名）。这三个部分在JWT里面分别对应英文句号分隔出来的三个串

        public static void Test()
        {
            //Test1();
            //Test2();
            //Test3();
            //Test4();
            Test5();
            //Test6();

        }

        private static void Test6()
        {
            var config = FtpConfigTest.Instance;
            //var ftpconfig = new FtpConfig()
            //{
            //    RootDirectory = config.RootDirectory,
            //    Encoding = EncodingEx.GetEncoding(config.Encoding),
            //    //Encoding = Encoding.ASCII
            //    AnonymousAccessPolicy = FtpAccessPolicy.ReadAndWrite
            //};

            var ftpconfig = new FtpConfig()
            {
                RootPathItems = new List<LocalPathItem>()
                {
                    new LocalPathItem("HBData", @"D:\HBData"),
                },
                Encoding = EncodingEx.GetEncoding("gb2312"),
                //Encoding = Encoding.ASCII
            };
            ftpconfig.Users = new List<FtpUserInfo>()
            {
                new FtpUserInfo("jec784","jec784")
        };
            var ftpServer = new FtpServer(ftpconfig);
            ftpServer.Start();



            Console.WriteLine("q exit");
            ConsoleKeyInfo consoleKey;
            while (true)
            {
                consoleKey = Console.ReadKey();
                if (consoleKey.Key == ConsoleKey.Q)
                {
                    break;
                }
            }

            ftpServer.Stop();
            ftpServer.Dispose();
        }

        private static void Test5()
        {
            var config = FtpConfigTest.Instance;
            //var ftpconfig = new FtpConfig()
            //{
            //    RootDirectory = config.RootDirectory,
            //    Encoding = EncodingEx.GetEncoding(config.Encoding),
            //    //Encoding = Encoding.ASCII
            //    AnonymousAccessPolicy = FtpAccessPolicy.ReadAndWrite
            //};

            var ftpconfig = new FtpConfig()
            {
                RootPathItems = new List<LocalPathItem>()
                {
                    new LocalPathItem("SoftFolder", @"E:\Soft"),
                    new LocalPathItem("VSFolder", @"D:\vs2022"),
                },
                Encoding = EncodingEx.GetEncoding("gb2312"),
                //Encoding = Encoding.ASCII
            };
            //ftpconfig.Users = new List<FtpUserInfo>()
            //{
            //    new FtpUserInfo("yf","qwe123")
            //    {
            //        VirtualPathItems=new List<LocalPathItem>()
            //        {
            //            new LocalPathItem("Soft", @"D:\Soft"),
            //            new LocalPathItem("temwav", @"D:\temwav"),
            //        }
            //    }
            //};
            var ftpServer = new FtpServer(ftpconfig);
            ftpServer.Start();




            Console.WriteLine("q exit");
            ConsoleKeyInfo consoleKey;
            while (true)
            {
                consoleKey = Console.ReadKey();
                if (consoleKey.Key == ConsoleKey.Q)
                {
                    break;
                }
            }

            ftpServer.Stop();
            ftpServer.Dispose();
        }



        private static void Test4()
        {
            //var eeee = EncodingEx.GetEncoding("IBM037");
            // var ret = sizeof(char);
            EncodingInfo[] es = Encoding.GetEncodings().OrderBy(t => { return t.Name; }).ToArray();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"{"Name",-40}{"DisplayName",-40}{"CodePage",-20}{"EncodingName"}");
            foreach (var e in es)
            {
                sb.AppendLine($"{e.Name,-40}{e.DisplayName,-40}{e.CodePage,-20}{e.GetEncoding().EncodingName}");
            }
            string str = sb.ToString();
        }

        private static void Test3()
        {
            //20220318080240
            var dt = DateTime.Parse("2022-03-18 16:02:40");
            var utcTime = dt.ToUniversalTime();
            string timeStr = utcTime.ToString("yyyyMMddHHmmss");

            //string timeStr = strs[1];
            var sb = new StringBuilder(19);
            for (int i = 0; i < timeStr.Length; i++)
            {
                //2022-03-18 08:02:40
                //2022 03 18 08 02 40
                //0123 45 67 89 1011 12 
                if (i == 4 || i == 6)
                {
                    sb.Append('-');
                }
                else if (i == 8)
                {
                    sb.Append(' ');
                }
                else if (i == 10 || i == 12)
                {
                    sb.Append(':');
                }

                sb.Append(timeStr[i]);
            }
            string timeStr2 = sb.ToString();
            DateTime utctime = DateTime.Parse(timeStr2);
            DateTime time = utctime.ToLocalTime();

            Console.WriteLine($"AltDirectorySeparatorChar:  {Path.AltDirectorySeparatorChar}");
            Console.WriteLine($"DirectorySeparatorChar: {Path.DirectorySeparatorChar}");
            Console.WriteLine($"PathSeparator:  {Path.PathSeparator}");
            Console.WriteLine($"VolumeSeparatorChar:    {Path.VolumeSeparatorChar}");
        }

        private static void Test2()
        {
            string srcFilePath, dstFilePath;
            long srcLength, dstLength;

            srcFilePath = @"D:\Soft\FontsIcon.rar";
            using (var fs = File.OpenRead(srcFilePath))
            {
                int count = 8;
                fs.Position = fs.Length - count;
                byte[] bufr = new byte[count];
                fs.Read(bufr, 0, count);

                string str = ConvertEx.BytesToHexadecimaString(bufr, false);
            }

            srcFilePath = @"D:\tmp\utilz\压缩ya_pk.zip";
            dstFilePath = @"D:\SelfCode\Demo\ftp\test\压缩ya_pk.zip";
            srcLength = FileEx.GetFileLength(srcFilePath);
            dstLength = FileEx.GetFileLength(dstFilePath);


            /********************************************************************************************************************
             * 2022-03-18 14:46:26 响应ftp127.0.0.1:60936：[125 Data connection already open; Transfer starting.]
             * 2022-03-18 14:46:26 接收到数据长度:65000
             * 2022-03-18 14:46:26 接收到数据长度:65000
             * 2022-03-18 14:46:26 接收到数据长度:65000
             * 2022-03-18 14:46:26 接收到数据长度:65000
             * 2022-03-18 14:46:26 接收到数据长度:65000
             * 2022-03-18 14:46:26 接收到数据长度:14237
             * 2022-03-18 14:46:26 ftp文件上传完成,接收到数据大小:339237
             * 2022-03-18 14:46:26 响应ftp127.0.0.1:60936：[226 Transfer complete.]
             ********************************************************************************************************************/

            srcFilePath = @"D:\tmp\utilz\getcolor.zip";
            dstFilePath = @"D:\SelfCode\Demo\ftp\test\getcolor.zip";
            // ftp文件上传完成,接收到数据大小:339237

            srcLength = FileEx.GetFileLength(srcFilePath);
            dstLength = FileEx.GetFileLength(dstFilePath);

            byte[] srcBuffer = File.ReadAllBytes(srcFilePath);
            byte[] dstBuffer = File.ReadAllBytes(dstFilePath);

            if (srcBuffer.Length != dstBuffer.Length)
            {
                return;
            }

            for (int i = 0; i < srcBuffer.Length; i++)
            {
                if (srcBuffer[i] != dstBuffer[i])
                {

                }
            }
        }

        private static void Test1()
        {
            string hexStr = @"31 31 2d 30 36 2d 31 38 20 20 30 38 3a 33 31 50
4d 20 20 20 20 20 20 20 20 20 20 20 20 20 20 31
34 33 38 30 38 36 20 37 7a 31 38 30 35 2d 78 36
34 2e 65 78 65 0d 0a 30 33 2d 32 34 2d 32 31 20
20 30 35 3a 34 31 50 4d 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 32 31 39 31 30 20 49 50
20 e8 a7 84 e5 88 92 5f 6e 65 77 2e 78 6c 73 78
0d 0a 30 33 2d 31 37 2d 32 32 20 20 31 31 3a 33
30 41 4d 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 31 38 34 35 32 20 49 50 20 e8 a7 84 e5
88 92 5f 6e 65 77 2e 7a 69 70 0d 0a 30 33 2d 31
37 2d 32 32 20 20 31 31 3a 33 30 41 4d 20 20 20
20 20 20 20 3c 44 49 52 3e 20 20 20 20 20 20 20
20 20 20 77 65 6e 6a 69 61 6e 6a 69 61 0d 0a 30
33 2d 31 37 2d 32 32 20 20 31 31 3a 33 30 41 4d
20 20 20 20 20 20 20 3c 44 49 52 3e 20 20 20 20
20 20 20 20 20 20 e5 8f b0 e4 bd 8d e6 8a a5 e6
96 87 0d 0a 30 33 2d 32 34 2d 32 31 20 20 30 35
3a 35 32 50 4d 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 33 34 39 36 36 20 e6 96 b0 e9 83
a8 e7 bd b2 e5 9b be 2e 76 73 64 78 0d 0a      
";
            hexStr = @"00d86125d242000c2964aa3f08004500004705a240008006e231c0a8c8c7c0a8c8c40015fb53e4959ee9082023cc5018201435f0000032353720222f222069732063757272656e74206469726563746f72792e0d0a";

            byte[] buffer = ConvertEx.HexadecimaStringToBytes(hexStr);
            //byte[] bbb2 = buffer.Skip(616).ToArray();
            string ftpListRes = Encoding.UTF8.GetString(buffer);
            string ftpListRes2 = Encoding.ASCII.GetString(buffer);
            //CodeGernerator.Create();

            //2021-03-24 05:52:23  =>  03-24-21  05:52PM 
            //yyyy-MM-dd_HH_mm_ss
            //string str = DateTime.Now.ToString("MM-dd-yy hh:mm tt");

            //string xx = string.Format("{0,21}", 23);
            //xx = "              1438086";


        }



        private static readonly string baseUrl = "http://127.0.0.1:8080/";



    }


    /// <summary>
    /// 配置类
    /// </summary>
    [ConfigRoot("FtpConfig")]
    public class FtpConfigTest : UtilZ.Dotnet.Ex.Config.IConfig
    {
        #region 单元实例
        private static FtpConfigTest _instance;
        public static FtpConfigTest Instance
        {
            get { return _instance; }
        }

        static FtpConfigTest()
        {
            _instance = Load();
        }
        #endregion



        #region 配置读写及初始化
        private const string _DEFAULT_CONFIGFILE_NAME = "config.xml";

        /// <summary>
        /// 加载配置
        /// </summary>
        /// <returns>配置对象</returns>
        private static FtpConfigTest Load()
        {
            try
            {
                var config = new FtpConfigTest();
                if (File.Exists(_DEFAULT_CONFIGFILE_NAME))
                {
                    try
                    {
                        ConfigHelper.ReadConfigFromFile(_DEFAULT_CONFIGFILE_NAME, config);
                    }
                    catch (Exception ex)
                    {
                        Loger.Error(ex);
                        config.InitDefaultValue();
                        SerializeToFile(config, _DEFAULT_CONFIGFILE_NAME);
                    }
                }
                else
                {
                    config.InitDefaultValue();
                    SerializeToFile(config, _DEFAULT_CONFIGFILE_NAME);
                }


                return config;
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
                return null;
            }
        }

        private static void SerializeToFile(FtpConfigTest config, string configFilePath)
        {
            DirectoryInfoEx.CheckFilePathDirectory(configFilePath);
            ConfigHelper.WriteConfigToXmlFile(config, configFilePath);
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        public void Save()
        {
            SerializeToFile(this, _DEFAULT_CONFIGFILE_NAME);
        }

        /// <summary>
        /// 
        /// </summary>
        public void InitDefaultValue()
        {

        }
        #endregion



        /// <summary>
        /// ftp根目录
        /// </summary>
        [ConfigItem("RootDirectory", "ftp根目录-设备编码")]
        public string RootDirectory { get; set; } = @"D:\Soft";

        /// <summary>
        /// 默认编码
        /// </summary>
        [ConfigItem("Encoding", "默认编码(gb2312/utf-8)")]
        public string Encoding { get; set; } = "gb2312";



    }
}
